<?php
declare (strict_types = 1);

namespace app\common\validate;

use app\common\model\user\SignForm;
use think\Validate;

class Email extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名'	=>	['规则1','规则2'...]
     *
     * @var array
     */	
	protected $rule = [
        'email'     =>'require|email',
        'captcha'   =>'require|print|checkCaptcha',
    ];
    
    /**
     * 定义错误信息
     * 格式：'字段名.规则名'	=>	'错误信息'
     *
     * @var array
     */	
    protected $message = [
        'email.require' => '邮箱不能为空.',
        'email.email' => '邮箱格式错误.',
        'captcha.require' => '验证码不能为空.',
        'captcha.print'   => '验证码无效',
        'captcha.checkCaptcha'     => '验证码无效.',
    ];

    /**
     * 验证邮箱验证码是否有效
     * @param string $value post提交的验证码
     * @param string $rule
     * @param array $formData
     * @return bool
     */
    public function checkCaptcha($value, $rule, $formData=[]){

        //获取session验证码数据
        $email_key = SignForm::EMAIL_CAPTCHA_KEY;
        $session = app()->session;
        $data = $session->get($email_key,'');

        //没有验证数据
        if (empty($data)){
            return false;
        }

        //判断邮箱是否匹配
        if ($data['email'] !== $formData['email']){
            return false;
        }

        //判断时间
        if((time() - $data['lifetime']) > $data['start_at']){
            return false;
        }

        //判断是否一致
        if(strtoupper($data['captcha']) !== strtoupper($value)){
            return false;
        }

        //清空captcha
        $session->delete($email_key);
        return true;
    }
}
